import { ref } from 'vue'
import { defineStore } from 'pinia'

import { toLogin } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref(getToken())
    const userName = ref('')
    const userId = ref(0)
    function login(name: string, password: string) {
      return new Promise((resolve, reject) => {
        toLogin(name, password)
          .then((res: any) => {
            userName.value = res.data.name
            userId.value = res.data.id
            setToken(res.token)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
    function logout() {
      token.value = ''
      userName.value = ''
      removeToken()
    }

    return { userName, userId, login, logout }
  },
  {
    persist: true
  }
)
